
package com.studiofortress.sf.util.structure;

import com.studiofortress.sf.graphics.GraphicsGL;
import com.studiofortress.sf.structure.Actor;
import java.awt.Color;

/**
 * This is a black screen that slowly fades out. When it is fully faded out it
 * will remove itself from the world.
 *
 * @author Joseph Lenton
 */
public class FadeInActor<G extends GraphicsGL> extends Actor<G>
{
    private long lastTime;
    private long endTime;
    private final long fadeTime;

    /**
     * @param fadeTime The amount of time, in milliseconds, for this to fade. Cannot be less than or equal to 0.
     */
    public FadeInActor(long fadeTime)
    {
        if (fadeTime <= 0) {
            throw new IllegalArgumentException("The given fade time cannot be less than or equal to 0.");
        }
        
        this.fadeTime = fadeTime;
        endTime = 0;
    }

    /**
     * Sets this actor to appear on top of everything else.
     */
    @Override
    protected void addedToWorld()
    {
        // debug info is typically at Integer.MAX_VALUE, so the fade goes just before it
        getWorld().setPaintOrder(this, Integer.MAX_VALUE-1);
    }

    /**
     * Increments the internal timer recording how long it's fading for.
     */
    @Override
    public void act()
    {
        if (endTime == 0) {
            endTime = System.currentTimeMillis() + fadeTime;
        }

        lastTime = System.currentTimeMillis();
        if (lastTime > endTime) {
            remove();
        }
    }

    /**
     * Paints the fade.
     * @param g The graphics contents for ths Actor to paint it's fade to.
     */
    @Override
    public void paint(G g)
    {
        int alpha = (int)(((float)(endTime-lastTime) / (float)fadeTime)*255f);
        g.setColor(0, 0, 0, alpha);
        g.fillRect(0, 0, getWorld().getWidth()+2, getWorld().getHeight()+2);
        g.setColor( 1f, 1f, 1f );
    }
}
